﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PhysicsControlModule.Models;

namespace PhysicsControlModule.Daos
{
    public class LabworkDao
    {
        public static List<Labwork> Load()
        {
            using (CmDbEntities db = new CmDbEntities())
            {
                return db.Labwork.ToList();
            }
        }

        public static List<Labwork> LoadAvailableLabworks(int userId)
        {
            using (CmDbEntities db = new CmDbEntities())
            {
                return (
                    from rlg in db.RelLabworkGroup
                    from l in db.Labwork
                    from u in db.User
                    from g in db.Group
                    where u.Id == userId
                    where u.GroupId == g.Id
                    where rlg.GroupId == g.Id
                    where rlg.LabworkId == l.Id
                    select l).ToList();
            }
        }

        public static Labwork GetById(int id)
        {
            using (CmDbEntities db = new CmDbEntities())
                return db.Labwork.First(m => m.Id == id);
        }


        public static int CountExperiment(int labworkId, int groupId)
        {
            using (CmDbEntities db = new CmDbEntities())
            {
                RelLabworkGroup relLabworkGroup = 
                    (
                        from rllq in db.RelLabworkGroup
                        where labworkId == rllq.LabworkId
                        where groupId == rllq.GroupId
                        select rllq).FirstOrDefault();
                return relLabworkGroup!=null ? relLabworkGroup.CountExperiments.GetValueOrDefault() : 0;
            }
        }

        public static List<RelLabworkGroup> LoadPublishedLabs(int tutorId)
        {
            using (CmDbEntities db = new CmDbEntities())
            {
                // TO DO: Write query for selecting published labs for current user
                return (
                    from lb in db.Labwork 
                    from rlg in db.RelLabworkGroup
                    where lb.Id == rlg.LabworkId
                    where rlg.PublisherId == tutorId
                    select rlg).ToList();
            }
        }
    }
}